//
//  CustemIMView.m
//  ipjsua
//
//  Created by YJ on 16/6/3.
//  Copyright © 2016年 Teluu. All rights reserved.
//

#import "CustemIMView.h"
#import <AVFoundation/AVFoundation.h>
#import <QuartzCore/QuartzCore.h>

#import "IMService.h"

@implementation CustemIMView

- (instancetype)init
{
    if (self = [super init]) {
        
        self.imView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        self.imView.backgroundColor = [UIColor blackColor];
        
        self.refuseBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, kScreenHeight - 40 - 60, (kScreenWidth-20-20)/3, 40)];
        [self.refuseBtn setTitle:@"拒绝" forState:UIControlStateNormal];
        [self.refuseBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.refuseBtn addTarget:self action:@selector(refuseRequest) forControlEvents:UIControlEventTouchUpInside];
        [self.imView addSubview:self.refuseBtn];
        
        self.agreeBtn = [[UIButton alloc] initWithFrame:CGRectMake( 10+(kScreenWidth-20-20)/3+10, kScreenHeight - 40 - 60,  (kScreenWidth-20-20)/3, 40)];
        [self.agreeBtn setTitle:@"接受" forState:UIControlStateNormal];
        [self.agreeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.agreeBtn addTarget:self action:@selector(agreeRequest) forControlEvents:UIControlEventTouchUpInside];
        [self.imView addSubview:self.agreeBtn];
        
        
        self.switchButton = [[UIButton alloc] initWithFrame:CGRectMake(10+(kScreenWidth-20-20)/3+10+(kScreenWidth-20-20)/3+10, kScreenHeight - 40 - 60,  (kScreenWidth-20-20)/3, 40)];
        [self.switchButton setTitle:@"切换" forState:UIControlStateNormal];
        [self.switchButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.switchButton addTarget:self action:@selector(switchRequest) forControlEvents:UIControlEventTouchUpInside];
        [self.imView addSubview:self.switchButton];
        
        [[IMService sharedInstance] IM_SetCodecSizeWithcodec:@"H264/97" Weight:(kScreenWidth) Hight:kScreenHeight];
        
        //使用扬声器
//        NSUInteger outputAudioPort = YES ? AVAudioSessionPortOverrideSpeaker : AVAudioSessionPortOverrideNone;
//        NSError* error = nil;
//        [[AVAudioSession sharedInstance] overrideOutputAudioPort:outputAudioPort error:&error];
        
    }
    return self;
}

- (void)refuseRequest
{
    if (_delegate && [_delegate respondsToSelector:@selector(refuseIMRequest)]) {
        [_delegate refuseIMRequest];
    }
}

- (void)agreeRequest
{
    if (_delegate && [_delegate respondsToSelector:@selector(agreeIMRequest)]) {
        [_delegate agreeIMRequest];
    }
}

-(void)switchRequest
{
    [[IMService sharedInstance] IM_SwitchCaptureWithCapId:3];
}

#pragma mark - 
- (void)showIMCallViewWithIMType:(IMType)imType
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imType = imType;
        [[UIApplication sharedApplication].keyWindow addSubview:self.imView];
    });
}

- (void)hideIMCallView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.localView removeFromSuperview];
        self.localView = nil;
        [self.distanceView removeFromSuperview];
        self.distanceView = nil;
        [self.imView removeFromSuperview];
    });
}

- (void)updateWithDistanceView:(UIView *)view
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.distanceView = view;
        self.distanceView.hidden = NO;
        self.distanceView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        
        NSArray *layers = view.layer.sublayers;
        
        for (CALayer *layertemp in layers)
        {
            if ([layertemp isKindOfClass:[AVCaptureVideoPreviewLayer class]])
            {
                layertemp.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            }
        }
        
        
        UITapGestureRecognizer * tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(switchDistanceAndLocalView)];
        [self.distanceView addGestureRecognizer:tapGesture1];
        
        UITapGestureRecognizer * tapDoubleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGesture:)];
        tapDoubleGesture.numberOfTapsRequired = 2;
        [self.distanceView addGestureRecognizer:tapDoubleGesture];
        
        [tapGesture1 requireGestureRecognizerToFail:tapDoubleGesture];
        
        if (![self.distanceView isDescendantOfView:self.imView]) {
            [self.imView addSubview:self.distanceView];
        }
        
        if ([self.refuseBtn isDescendantOfView:self.imView]) {
            [self.imView bringSubviewToFront:self.refuseBtn];
        }
        if ([self.agreeBtn isDescendantOfView:self.imView]) {
            [self.imView bringSubviewToFront:self.agreeBtn];
        }
        
        if ([self.switchButton isDescendantOfView:self.imView]) {
            [self.imView bringSubviewToFront:self.switchButton];
        }
    });
}

- (void)updateWithLocalView:(UIView *)view displayBigNative:(BOOL)displayBigNative
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.localView = view;
        self.localView.hidden = NO;
        
        if (displayBigNative)
        {
            self.localView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        }
        else
        {
            self.localView.frame = CGRectMake(kScreenWidth - 100 - 20, kScreenHeight - 100 - 200, 100, 200);
        }
        
        NSArray *layers = view.layer.sublayers;
        
        if (layers.count>0)
        {
            for (CALayer *layertemp in layers)
            {
                if ([layertemp isKindOfClass:[AVCaptureVideoPreviewLayer class]])
                {
                    if (displayBigNative)
                    {
                         layertemp.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
                    }
                    else
                    {
                         layertemp.frame = CGRectMake(0, 0, 100, 200);
                    }
                }
            }
        }
        else
        {
            self.localView.layer.bounds = CGRectMake(0, 0, 100, 200);
        }
        
        UITapGestureRecognizer * tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(switchDistanceAndLocalView)];
        [self.localView addGestureRecognizer:tapGesture2];
        
        UIPanGestureRecognizer * panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureToEdge:)];
        panGesture.minimumNumberOfTouches = 1;
        panGesture.maximumNumberOfTouches = 1;
        [self.localView addGestureRecognizer:panGesture];
        
        if (![self.localView isDescendantOfView:self.imView]) {
            [self.imView addSubview:self.localView];
        }
        
        [self.imView bringSubviewToFront:self.localView];
        
        if ([self.refuseBtn isDescendantOfView:self.imView]) {
            [self.imView bringSubviewToFront:self.refuseBtn];
        }
        if ([self.agreeBtn isDescendantOfView:self.imView]) {
            [self.imView bringSubviewToFront:self.agreeBtn];
        }
        
        if ([self.switchButton isDescendantOfView:self.imView]) {
            [self.imView bringSubviewToFront:self.switchButton];
        }
        
    });
}

- (void)switchDistanceAndLocalView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView * tempLocalView = self.localView;
        UIView * tempDistanceView = self.distanceView;
        
        [self updateWithLocalView:tempDistanceView displayBigNative:NO];
        [self updateWithDistanceView:tempLocalView];
    });
}

- (void)panGestureToEdge:(UIPanGestureRecognizer *)panGeture
{
    if (panGeture.state != UIGestureRecognizerStateEnded && panGeture.state != UIGestureRecognizerStateFailed) {
        
        CGPoint longGesturePos = [panGeture locationInView:panGeture.view.superview];
        panGeture.view.center = longGesturePos;
        
    } else if (panGeture.state == UIGestureRecognizerStateEnded || panGeture.state == UIGestureRecognizerStateFailed) {
        
        CGPoint longGesturePos = [panGeture locationInView:panGeture.view.superview];
    }
}

/*前后摄像头切换*/
- (void)doubleTapGesture:(UITapGestureRecognizer *)tapDoubleGesture
{

}

@end
